package com.effort.com.effort.excle.service;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.hutool.core.util.ObjectUtil;
import com.effort.com.effort.excle.core.exception.ParamException;
import com.effort.com.effort.excle.param.PointValue;
import com.effort.com.effort.excle.pool.InfluxDbPool;
import com.effort.com.effort.excle.query.BaseQuery;
import com.effort.com.effort.excle.utils.DateTimeExcleUtils;
import com.effort.com.effort.excle.utils.ExcleExportDate;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.influxdb.InfluxDB;
import org.influxdb.dto.Query;
import org.influxdb.dto.QueryResult;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ExcleService {

    @Resource
    private InfluxDbPool influxDbPool;

    public Workbook excle(BaseQuery query) throws ParseException {
        if (query.getTagNames() == null || query.getTagNames().length == 0) {
            throw new ParamException("请选择对应的测点");
        }
        String key = query.getKey();
        InfluxDB influxdb = influxDbPool.getConnectionByKey(key);

        /// 计算出需要导出逇时间片端来
        List<ExcleExportDate> transform = DateTimeExcleUtils.transform(query.getStartDate(), query.getEndDate());

        Workbook workbook = null;
        List<Map<String, Object>> all = Lists.newArrayList();
        for (String tag : query.getTagNames()) {
            ExportParams deptExportParams = new ExportParams();
            // 设置sheet得名称
            deptExportParams.setSheetName(tag);
            // 创建sheet1使用得map
            Map<String, Object> dataExportMap = new HashMap<>();
            // title的参数为ExportParams类型，目前仅仅在ExportParams中设置了sheetName
            dataExportMap.put("title", deptExportParams);
            // 模版导出对应得实体类型
            dataExportMap.put("entity", PointValue.class);
            // sheet中要填充得数据
            List<PointValue> list = Lists.newArrayList();
            dataExportMap.put("data", list);
            all.add(dataExportMap);

            for (ExcleExportDate bean : transform) {
                query.setStartDate(bean.getStartDate());
                query.setEndDate(bean.getEndDate());
                Query ql = new Query("select first(value) from " + "\"" + tag + "\"" + handleSqlOther(query), query.getDatabase());
                QueryResult result = influxDbPool.getConnectionByKey(query.getKey()).setDatabase(query.getDatabase()).query(ql);
                // 查询出的结果集
                List<QueryResult.Series> series = result.getResults().get(0).getSeries();
                // 当前的结果集是没有数据的
                if (series == null) {
                    continue;
                }
                List<List<Object>> values = series.get(0).getValues();
                for (List<Object> value : values) {
                    PointValue pv = new PointValue();
                    pv.setTime(cn.hutool.core.date.DateUtil.format(new DateTime(value.get(0).toString()).toDate(), "yyyy-MM-dd hh:mm:ss"));
                    String realValue;
                    if (ObjectUtil.isNull(value.get(1))) {
                        realValue = StringUtils.EMPTY;
                    } else {
                        realValue = value.get(1).toString();
                    }
                    pv.setValue(realValue);
                    list.add(pv);
                }
            }
        }
        // 最终返回一个WorkBook
        return ExcelExportUtil.exportExcel(all, ExcelType.HSSF);

    }

    // 处理sql的其它部分内容
    private String handleSqlOther(BaseQuery query) {
        StringBuilder sb = new StringBuilder();
        sb.append(" where time < '")
                .append(query.getEndDate())
                .append("'")
                .append(" and time > '")
                .append(query.getStartDate())
                .append("'")
                .append(" group by time(")
                .append(query.getInterval())
                .append(query.getIntervalUnit())
                .append(")");
        return sb.toString();
    }

    private List<Object> handleValue(QueryResult result, int i) {
        return result.getResults().get(0).getSeries().get(i).getValues().get(1);
    }

    private String handleTagNames(String[] tagNames) {
        StringBuilder builder = new StringBuilder();
        for (String tagName : tagNames) {
            builder.append("\"").append(tagName).append("\"").append(",");
        }
        return builder.substring(0, builder.length() - 1);
    }
}
